1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package groovy.swing;
20
21 import java.util.logging.Level;
22 import java.util.logging.Logger;
23
24 import javax.swing.table.AbstractTableModel;
25
26
27
28
29
30
31 public class MyTableModel extends AbstractTableModel {
32
33 private static final Logger log = Logger.getLogger(MyTableModel.class.getName());
34
35 public MyTableModel() {
36 }
37
38 final String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };
39 final Object[][] data = { { "Mary", "Campione", "Snowboarding", Integer.valueOf(5), new Boolean(false)}, {
40 "Alison", "Huml", "Rowing", Integer.valueOf(3), new Boolean(true)
41 }, {
42 "Kathy", "Walrath", "Chasing toddlers", Integer.valueOf(2), new Boolean(false)
43 }, {
44 "Mark", "Andrews", "Speed reading", Integer.valueOf(20), new Boolean(true)
45 }, {
46 "Angela", "Lih", "Teaching high school", Integer.valueOf(4), new Boolean(false)
47 }
48 };
49
50 public int getColumnCount() {
51 return columnNames.length;
52 }
53
54 public int getRowCount() {
55 return data.length;
56 }
57
58 public String getColumnName(int col) {
59 return columnNames[col];
60 }
61
62 public Object getValueAt(int row, int col) {
63 return data[row][col];
64 }
65
66
67
68
69
70
71
72 public Class getColumnClass(int c) {
73 return getValueAt(0, c).getClass();
74 }
75
76
77
78
79
80 public boolean isCellEditable(int row, int col) {
81
82
83 if (col < 2) {
84 return false;
85 }
86 else {
87 return true;
88 }
89 }
90
91
92
93
94
95 public void setValueAt(Object value, int row, int col) {
96 if (log.isLoggable(Level.FINE)) {
97 log.fine(
98 "Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
99 }
100
101 if (data[0][col] instanceof Integer && !(value instanceof Integer)) {
102
103
104
105
106
107
108
109 try {
110 data[row][col] = Integer.valueOf(value.toString());
111 fireTableCellUpdated(row, col);
112 }
113 catch (NumberFormatException e) {
114 log.log(Level.SEVERE, "The \"" + getColumnName(col) + "\" column accepts only integer values.");
115 }
116 }
117 else {
118 data[row][col] = value;
119 fireTableCellUpdated(row, col);
120 }
121 }
122
123 }